package ntu.metaweb.http;

import java.io.IOException;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLDecoder;
import java.util.HashMap;

import ntu.metaweb.Metaweb;
import ntu.metaweb.service.Service;
import ntu.metaweb.storage.FiveStarRating;
import ntu.metaweb.storage.PagesWithTagKey;
import ntu.metaweb.storage.Tag;
import ntu.metaweb.storage.WebPageQuery;
import ntu.metaweb.storage.WebPageQueryKey;
import ntu.metaweb.update.NewTag;
import ntu.metaweb.update.UpdatePageRating;
import ntu.p2p.dht.DHTContent;
import ntu.p2p.dht.messaging.DHTUpdateObjectMessage;
import rice.Continuation;
import rice.pastry.Id;

import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;

public class AddTagHandler implements CommandHandler {

	@Override
	public void handleCommand(final HttpExchange exchange,
			final HashMap<String, String> params) throws IOException {
		if (params.get("url_parameter").equals("null"))
			params.put("url_parameter", "");
		final String temp = params.get("url") + params.get("url_parameter");
		final WebPageQueryKey key = new WebPageQueryKey(
				URLDecoder.decode(params.get("url"), "UTF-8"), 
				URLDecoder.decode(params.get("url_parameter"), "UTF-8"));
		final URL url = new URL(URLDecoder.decode(temp, "UTF-8"));
		Metaweb.getInstance().getDhtApplication().lookup(key, 
				new Continuation<DHTContent,Exception>() {

					@Override
					public void receiveException(Exception exception) {

					}

					@Override
					public void receiveResult(DHTContent result) {
						WebPageQuery webpagequery = (WebPageQuery) result;
						final NewTag newtag = new NewTag(url, params.get("tag"), params.get("username"), 
								webpagequery.getTitle(), webpagequery.getAverageRating());
						DHTUpdateObjectMessage updateMessage = new DHTUpdateObjectMessage(key, 
								newtag);
						Metaweb.getInstance().getDhtApplication().update(key, updateMessage, 
								new Continuation<Object, Exception>() {

									@Override
									public void receiveException(Exception exception) {
										// TODO Auto-generated method stub
										
									}

									@Override
									public void receiveResult(Object result) {
										System.out.println("update successs");
										
										// add to pages with tag
										final PagesWithTagKey pageswithtagkey = new PagesWithTagKey(params.get("tag"));
										Metaweb.getInstance().getDhtApplication().lookup(pageswithtagkey, 
												new Continuation<DHTContent,Exception>() {

													@Override
													public void receiveException(Exception exception) {

													}

													@Override
													public void receiveResult(DHTContent result) {
														if (result == null) {
															Service.insertPagesWithTag(params.get("tag"), newtag);
														} else {
															DHTUpdateObjectMessage updateMessage = new DHTUpdateObjectMessage(
																	pageswithtagkey, newtag);
															Metaweb.getInstance().getDhtApplication().update(key, updateMessage, 
																	new Continuation<Object, Exception>() {
									
																		@Override
																		public void receiveException(Exception exception) {
																			// TODO Auto-generated method stub
																			
																		}
									
																		@Override
																		public void receiveResult(Object result) {
																			System.out.println("update successs");
																			//onReceiveResult(exchange, result);
																		}
															});
														}
													}
										});
										onReceiveResult(exchange, result);
									}
						});

					}
		});
		
		
	}

	@SuppressWarnings("restriction")
	protected void onReceiveResult(HttpExchange exchange, Object result) {
		try {
			Headers responseHeaders = exchange.getResponseHeaders();
			responseHeaders.set("Content-Type", "text/xml");
			exchange.sendResponseHeaders(200, 0);

			OutputStream responseBody = exchange.getResponseBody();
			String temp = "<xmlresponse>\n" 
					+ "<returncode>1</returncode>\n"
					+ "</xmlresponse>";
			responseBody.write(temp.getBytes());
			responseBody.close();
			exchange.close();
			System.out.println("close add tag handler");

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			exchange.close();
			System.out.println("close add tag handler");
		}
	}

}
